﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TravelLink.DAL;
using DevExpress.Web.ASPxTreeView;

namespace TravelLink.WebApp.Admin
{
    public partial class AdminRole : System.Web.UI.Page, ICallbackEventHandler
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.CheckResponse("8002");
            if (!this.IsPostBack)
            {
                var dc = DAL.DataContextFactory.Create();
                foreach (var group in dc.TL_FunctionGroup.OrderBy(t => t.Seq).ToList())
                {
                    var node = this.ASPxTreeView1.Nodes.Add(group.Name,group.Idx.ToString());
                    node.DataItem = group;
                    foreach (var func in group.TL_Function.OrderBy(t => t.Seq).ToList())
                    {
                        node.Nodes.Add(func.Name,func.Idx.ToString());
                    }
                    node.AllowCheck = false;
                }
                this.ASPxTreeView1.ExpandAll();
            }
        }

        protected void ldsRole_Inserting(object sender, LinqDataSourceInsertEventArgs e)
        {
            ((TL_Role)e.NewObject).Idx = Guid.NewGuid();
            ((TL_Role)e.NewObject).PrivilegeStr = string.Empty;
        }

        protected void ASPxGridView1_FocusedRowChanged(object sender, EventArgs e)
        {
            TravelLink.DAL.TL_Role role = ((TravelLink.DAL.TL_Role)(this.ASPxGridView1.GetRow(this.ASPxGridView1.FocusedRowIndex)));
            if (role != null)
            {
                this.ASPxTreeView1.Nodes[0].Checked = true;
            }
        }

        private string CallBackValue = string.Empty;

        #region ICallbackEventHandler 成员

        public string GetCallbackResult()
        {
            return CallBackValue;
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            try
            {
                string[] eArg = eventArgument.Split(';');
                int rowid = int.Parse(eArg[0]);
                Guid idx = Guid.Parse(eArg[1]);
                string privstr = eArg[2];
                var dc = DAL.DataContextFactory.Create();
                var obj=dc.TL_Role.Where(t => t.Idx == idx).FirstOrDefault();
                obj.PrivilegeStr = privstr;
                dc.SubmitChanges();
                TL_Role rowobj = (TL_Role)this.ASPxGridView1.GetRow(rowid);
                rowobj.PrivilegeStr = privstr;
                CallBackValue = "";
            }
            catch (Exception ex)
            {
                this.CallBackValue = ex.Message;
            }
        }

        #endregion
    }
}